<template>
  <div id="module" class="main-box">
    <el-button type="primary" icon="el-icon-arrow-left" @click="prev">
      {{ $t('返回') }}
    </el-button>
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin-bottom: 16px"
      @click="goAdd"
    >
      {{ $t('添加') }}
    </el-button>
    <BaseDialog
      :title="addForm.id ? $t('编辑') : $t('添加')"
      :dialog-show.sync="dialogShow"
      width="50%"
      class="field"
      style="margin-top: -5vh"
      footer
      @submit="submit"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        class="addForm"
        label-position="top"
      >
        <el-form-item :label="$t('表单标题')" prop="form_title">
          <el-input v-model="addForm.form_title" />
        </el-form-item>
        <el-form-item :label="$t('数据表字段')" prop="table_field">
          <el-input
            v-model="addForm.table_field"
            :disabled="addForm.id ? true : false"
          />
        </el-form-item>
        <el-form-item :label="$t('数据类型')" prop="type">
          <el-select
            v-model="addForm.type"
            :placeholder="$t('请选择数据类型')"
            :disabled="addForm.id ? true : false"
          >
            <el-option
              v-for="item in options"
              :key="item.label"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <div v-if="addForm.type == '关联字段'">
          <el-form-item :label="$('关联关系')" prop="relation">
            <el-select v-model="settings.relation" @change="changeRelation">
              <el-option :label="$t('一对一')" value="has_one" />
              <el-option :label="$t('一对多')" value="has_many" />
              <el-option :label="$t('多对多')" value="belongs_to_many" />
              <el-option :label="$t('多对一')" value="belongs_to" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="settings.relation == 'belongs_to_many'" label=" ">
            <el-alert
              style="line-height: 12px"
              :title="`${$t('温馨提示')}：`"
              :description="$t('关联字段提示')"
              type="error"
              :closable="false"
            />
          </el-form-item>
          <el-form-item :label="$t('关联表')">
            <el-select
              v-model="settings.table"
              filterable
              @change="changeTable"
            >
              <el-option
                v-for="(item, index) in moduleTable"
                :key="index"
                :label="item.table"
                :value="item.table"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('关联字段')">
            <el-select v-model="settings.foreign_key">
              <el-option
                v-for="(item, index) in moduleField"
                :key="index"
                :label="
                  item.column_comment
                    ? item.column_name + '(' + item.column_comment + ')'
                    : item.column_name
                "
                :value="item.column_name"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="settings.relation == 'belongs_to_many'"
            :label="$t('被关联字段')"
          >
            <el-select v-model="settings.local_key">
              <el-option
                v-for="(item, index) in associatedField"
                :key="index"
                :label="
                  item.column_comment
                    ? item.column_name + '(' + item.column_comment + ')'
                    : item.column_name
                "
                :value="item.column_name"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item :label="$t('排序')" prop="order">
          <el-select v-model="addForm.order">
            <el-option label="ID" value="id" />
            <el-option
              v-for="item in orderList"
              :key="item.id"
              :label="item.form_title"
              :value="item.table_field"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('状态')" prop="status">
          <el-select v-model="addForm.status">
            <el-option :label="$t('正常')" :value="1" />
            <el-option :label="$t('禁用')" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('字段为空')" prop="is_null">
          <el-select v-model="addForm.is_null">
            <el-option :label="$t('允许')" :value="1" />
            <el-option :label="$t('不允许')" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="
            addForm.type == $t('单选') ||
            addForm.type == $t('多选') ||
            addForm.type == $t('列表多选') ||
            addForm.type == $t('列表') ||
            addForm.type == $t('开关')
          "
          :label="$t('扩展信息')"
          prop="attach_data"
        >
          <el-input
            v-model="addForm.attach_data"
            placeholder="$t('扩展信息提示')"
            type="textarea"
          />
        </el-form-item>
        <el-form-item :label="$t('验证规则')">
          <el-select
            v-model="addForm.form_validate"
            multiple
            :placeholder="$t('请选择验证规则')"
          >
            <el-option
              v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('默认值')" prop="default">
          <el-input v-model="addForm.default" />
        </el-form-item>
        <el-form-item :label="$t('提示信息')" prop="placeholder">
          <el-input v-model="addForm.placeholder" />
        </el-form-item>
        <el-form-item :label="$t('字段长度')" prop="length">
          <el-input v-model="addForm.length" />
        </el-form-item>

        <!-- <el-form-item label="附表" prop="database_table">
          <el-input v-model="addForm.database_table" />
        </el-form-item> -->
        <!-- <el-form-item label="设为系统模型">
          <el-select v-model="addForm.is_system">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="2" />
          </el-select>
        </el-form-item> -->
      </el-form>
    </BaseDialog>
    <el-table :data="orderData">
      <el-table-column label="ID" prop="id" width="60px" />
      <el-table-column :label="$t('名称')" prop="form_title" />
      <el-table-column :label="$t('字段')" prop="table_field" />
      <el-table-column :label="$t('数据类型')" prop="type" />
      <el-table-column :label="$t('排序')" prop="order" />
      <el-table-column :label="$t('允许为空')">
        <template slot-scope="scope">
          <span v-if="scope.row.is_null == 1">{{ $t('是') }}</span>
          <span v-if="scope.row.is_null == 2">{{ $t('否') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('验证规则')" prop="form_validate" />
      <el-table-column :label="$t('状态')">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 1">{{ $t('正常') }}</span>
          <span v-else-if="scope.row.status == 2">{{ $t('禁用') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" width="150px" fixed="right">
        <template slot-scope="scope">
          <EditBtn @click="editor(scope.row)" />
          <DelBtn
            @success="del(scope.row)"
            :confirm-content="$t('删除该模型字段')"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import moduleApi from '@/api/module.js'
import settings from '@/settings'
export default {
  data() {
    return {
      module_id: '', // 模型id
      options: [
        { label: this.$t('单行文本') },
        { label: this.$t('多行文本') },
        { label: this.$t('富文本编辑器') },
        { label: this.$t('整数') },
        { label: this.$t('数字') },
        { label: this.$t('日期') },
        { label: this.$t('时间') },
        { label: this.$t('日期时间') },
        { label: this.$t('日期时间区间') },
        { label: this.$t('列表') },
        { label: this.$t('列表多选') },
        { label: this.$t('图片') },
        { label: this.$t('多图') },
        { label: this.$t('视频') },
        { label: this.$t('多视频') },
        { label: this.$t('文件') },
        { label: this.$t('多文件') },
        { label: this.$t('开关') },
        { label: this.$t('单选') },
        { label: this.$t('多选') },
        { label: this.$t('关联字段') },
        { label: this.$t('金额') }
      ],
      options2: [
        {
          value: 'require',
          label: this.$t('必填')
        },
        {
          value: 'number',
          label: this.$t('整数')
        },
        {
          value: 'alpha',
          label: this.$t('字母')
        },
        {
          value: 'date',
          label: this.$t('日期')
        },
        {
          value: 'time',
          label: this.$t('时间')
        },
        {
          value: 'email',
          label: this.$t('邮箱')
        }
      ],
      type: '', // 类型
      form_validate: '', // 验证规则
      orderData: [], //
      dialogShow: false,
      addForm: {
        id: '',
        form_title: '',
        table_field: '',
        type: '',
        order: '',
        status: '',
        is_null: '',
        status: '',
        form_validate: '',
        default: '',
        placeholder: '',
        length: '',
        is_system: '',
        relation: '',
        settings: {}
      },
      settings: {
        relation: 'has_one',
        table: '',
        foreign_key: '',
        local_key: '',
        table_name: ''
      },
      rules: {
        // relation: [
        //   { required: 'true', message: '请选择关联关系', trigger: 'change' }
        // ],
        form_title: [
          {
            required: 'true',
            message: this.$t('请输入表单名'),
            trigger: 'blur'
          }
        ],
        table_field: [
          {
            required: 'true',
            message: this.$t('请输入字段名'),
            trigger: 'blur'
          }
        ],
        order: [
          { required: 'true', message: this.$t('请选择排序'), trigger: 'blur' }
        ],
        type: [
          {
            required: 'true',
            message: this.$t('请选择模型类型'),
            trigger: 'blur'
          }
        ],
        status: [
          { required: 'true', message: this.$t('请选择状态'), trigger: 'blur' }
        ],
        is_null: [
          {
            required: 'true',
            message: this.$t('请选择是否允许字段为空'),
            trigger: 'blur'
          }
        ],
        attach_data: [
          {
            required: 'true',
            message: this.$t('请输入扩展信息'),
            trigger: 'blur'
          }
        ]
      },
      searchForm: {
        title: ''
      },
      val: {},
      orderList: [],
      moduleTable: [], // 模型表
      moduleField: [], // 关联字段
      associatedField: [], // 被关联字段
      table_name: ''
    }
  },
  created() {
    this.addForm.module_id = this.$route.query.id
    this.getList()
    this.getModuleTable()
    this.getModuleInfo()
  },
  methods: {
    // 模型详情
    getModuleInfo() {
      moduleApi.moduleInfo({ id: this.$route.query.id }).then(res => {
        if (res.code == 0) {
          const database_table = res.data.database_table
          this.getAssociatedField(database_table)
        }
      })
    },
    // 获取被关联字段
    getAssociatedField(val) {
      moduleApi.moduleField({ table: val }).then(res => {
        if (res.code == 0) {
          this.associatedField = res.data
          // if (res.data.length > 0) {
          //   this.settings.local_key = res.data[0].column_name
          // } else {
          //   this.settings.local_key = ''
          // }
        }
      })
    },
    // 切换关系
    changeRelation(val) {
      if (val != 'belongs_to_many') {
        this.settings.local_key = ''
      }
    },
    // 切换关联表
    changeTable(val) {
      this.table_name = val
      this.settings.table_name = val
      this.getModuleField()
    },
    // 获取关联表
    getModuleTable() {
      moduleApi.moduleTable().then(res => {
        if (res.code == 0) {
          this.moduleTable = res.data
          this.table_name = res.data[0].table
          this.settings.table = res.data[0].table
          this.settings.table_name = res.data[0].table
          this.getModuleField()
        }
      })
    },
    // 获取关联字段
    getModuleField() {
      moduleApi.moduleField({ table: this.table_name }).then(res => {
        if (res.code == 0) {
          this.moduleField = res.data

          if (res.data.length > 0) {
            this.settings.foreign_key = res.data[0].column_name
          } else {
            this.settings.foreign_key = ''
          }
        }
      })
    },
    // 新增
    goAdd() {
      this.orderList = this.orderData
      this.addForm = {
        module_id: this.addForm.module_id,
        form_title: '',
        table_field: '',
        type: '',
        order: '',
        status: 1,
        is_null: 1,
        form_validate: '',
        default: '',
        placeholder: '',
        length: '',
        is_system: ''
      }
      this.$nextTick(() => {
        this.dialogShow = true
      })
    },
    // 编辑
    editor(row) {
      const arr = this.orderData

      this.orderList = []
      arr.forEach(el => {
        if (el.id != row.id) {
          this.orderList.push(el)
        }
      })

      if (row.form_type == 'reference') {
        this.table_name = row.settings.table_name
        this.getModuleField()
        this.settings = row.settings
      }

      this.addForm = row
      delete this.addForm.create_time
      delete this.addForm.update_time

      this.addForm.id = row.id
      this.dialogShow = true
    },
    submit() {
      if (this.addForm.type == '关联字段') {
        this.addForm.settings = this.settings
      }

      // return
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (!this.addForm.id) {
            moduleApi.fieldSave({ ...this.addForm }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.getList()
              }
            })
          } else {
            moduleApi.fieldUpdate({ ...this.addForm }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.dialogShow = false
                this.getList()
              }
            })
          }
        } else {
          this.$message.error(this.$t('请填写必要信息'))
        }
      })
    },
    // 查看
    check() {},
    // 删除
    del(row) {
      moduleApi
        .fieldDelete({ id: row.id, module_id: row.module_id })
        .then(res => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.getList()
          }
        })
    },
    // 搜索
    search(searchForm) {
      this.$refs.searchForm.validate(valid => {
        // this.page.currentPage = 1
        this.getList(this.val)
      })
    },
    // 重置搜索框
    reset(searchForm) {
      this.searchForm.title = ''
    },
    // 模型列表
    getList() {
      // this.val.page = this.page.currentPage
      // this.val.limit = this.page.size
      this.val.module_id = this.addForm.module_id

      // this.val.title = this.searchForm.title
      moduleApi.fieldList(this.val).then(res => {
        this.orderData = res.data

        // this.page.total = res.count
      })
    },
    // 禁用
    disableUser(row) {
      this.addForm.status = row.status
      this.addForm.id = row.id
      this.submit()
      // moduleApi.changeStatus({ id: row.id, status: row.status }).then(res => {
      //   if (res.code == 0) {
      //     this.$message.success(res.msg)
      //     this.getList()
      //   }
      // })
    },

    // 返回上一页
    prev() {
      this.$router.push({ name: 'Model' })
    }
  }
}
</script>
<style lang="scss">
#module {
  .link {
    .el-select {
      width: 100%;
    }
  }
  .addForm .el-form-item__content {
    .el-select {
      width: 100%;
    }
  }
}
</style>
<style scoped lang="scss">
.el-table {
  margin-bottom: 20px;
}
.search {
  min-width: 1350px;
  background-color: #fff;
  padding: 35px 30px 20px;
  border-radius: 5px;
}
.el-form-item {
  width: 100%;
}
.el-dialog {
  margin-top: 5vh !important;
}
</style>
